package com.tm.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LoggingHandler;

public class NettyServer {

    public void run() {
        //创建事件线程组，
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        //创建服务启动器
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            //给服务启动器配置参数
            serverBootstrap.group(boosGroup, workerGroup)//绑定线程组
                    .channel(NioServerSocketChannel.class)//Nio模式
                    .option(ChannelOption.SO_BACKLOG, 1024)//标识当服务器请求处理线程全满时，用于临时存放已完成三次握手的请求的队列的最大长度。主要是作用于boss线程，用于处理新连接
                    .childOption(ChannelOption.SO_KEEPALIVE, true)//启用心跳保活机制,主要作用与worker线程，也就是已创建的channel。
                    .handler(new LoggingHandler("DEBUG"))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
//                                    .addLast(new StringDecoder())//加载编解码器
//                                    .addLast(new StringEncoder())
                                    .addLast(new NettyServerHandler());//加载handler处理器
                        }
                    });

            //绑定端口,这里用到的是ChannelFuture类
            ChannelFuture future = serverBootstrap.bind(9989
            ).sync();
            System.out.println("服务端启动成功....");
            //关闭通道
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //在这里关闭事件线程组,释放资源
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new NettyServer().run();
    }

}
